package com.kindey.httpclientdemo.demo;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class HttpURLconnectionSimpleDemo {
    public static final Logger logger = LoggerFactory.getLogger(HttpURLconnectionSimpleDemo.class);

    public String sendGet(String url) {
        String result = "";
        BufferedReader in = null;


        try {
            URL httpUrl = new URL(url);

            HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();

            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5 * 1000);
            connection.setReadTimeout(5 * 1000);

            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Charsert", "UTF-8"); //设置请求编码
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            connection.connect();

            if (connection.getResponseCode() == 200) {
                // 定义 BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } else {

            }
            connection.disconnect();

        } catch (Exception e) {
            StringBuilder sb = new StringBuilder();
            sb.append("\n").append(e.toString()).append("\n");
            StackTraceElement[] stackTrace = e.getStackTrace();
            for (StackTraceElement s : stackTrace) {
                sb.append("    ").append(s.toString()).append("\n");
            }
            logger.error("ExceptionMessage:{}", sb.toString());
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return result;
    }

    public String sendPost(String url) throws Exception {
        String result = "";

        URL httpUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
        connection.setRequestProperty("Accept-Charset", "UTF-8");
        connection.setRequestProperty("connection", "keep-Alive");
        connection.setRequestMethod("POST");
        connection.setConnectTimeout(5 * 1000);
        connection.setReadTimeout(5 * 1000);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        connection.connect();

        String jsonstring = getJOSNString();
        if (!StringUtils.isEmpty(jsonstring)) {
            BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());
            out.write(jsonstring.getBytes());
            out.flush();
            out.close();

            result = IOUtils.toString(connection.getInputStream(), "UTF-8");
        }

        connection.disconnect();
        return result;
    }

    public String getJOSNString() {
        JSONObject jsonobject = new JSONObject();
        JSONObject jsonobject1 = new JSONObject();
        JSONObject jsonobject2 = new JSONObject();
        jsonobject2.put("name", "jingchenyong");
        jsonobject1.put("match", jsonobject2);
        jsonobject.put("query", jsonobject1);
        String jsonstring = jsonobject.toJSONString();
        return jsonstring;
    }
}
